package com.shop.service;

import cn.hutool.core.util.ObjectUtil;
import com.shop.dao.CoinsMapper;
import com.shop.dao.HistoryMapper;
import com.shop.dto.CoinOptionDto;
import com.shop.dto.UserInfo;
import com.shop.entity.CoinsEntity;
import com.shop.entity.HistoryEntity;
import com.shop.local.UserInfoLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author wzby
 * @date 2022-12-02 13:24:15
 */
@Service
public class MemberCoinsService {

    @Autowired
    private CoinsMapper coinsMapper;
    @Autowired
    private HistoryMapper historyMapper;

    @Transactional
    public void send(CoinOptionDto coinOptionDto){
        Integer memberId = coinOptionDto.getMemberId();

        CoinsEntity coinsEntity = coinsMapper.select(memberId);

        Integer origin = 0;
        if(ObjectUtil.isEmpty(coinsEntity)){
            CoinsEntity coins = new CoinsEntity();
            coins.setId(memberId);
            coins.setQty(coinOptionDto.getOptionQty());
            coinsMapper.insert(coins);
            origin = 0;
        }else {
            coinsMapper.update(memberId, coinOptionDto.getOptionQty());
            origin = coinsEntity.getQty();
        }
        HistoryEntity historyEntity  =  new HistoryEntity();
        historyEntity.setBrief(coinOptionDto.getBrief());
        historyEntity.setCreateBy(coinOptionDto.getCreateBy());
        historyEntity.setOptionType(coinOptionDto.getOptionType());
        historyEntity.setOptionQty(coinOptionDto.getOptionQty());
        historyEntity.setRefId(coinOptionDto.getRefId());
        historyEntity.setMemberId(coinOptionDto.getMemberId());

        historyEntity.setQty0(origin);
        historyEntity.setQty1(origin+coinOptionDto.getOptionQty());

        historyMapper.insert(historyEntity);

    }

    public Integer selectCoinQty(){
        UserInfo userInfo = UserInfoLocal.get();
        return coinsMapper.selectCoinsQty(userInfo.getMemberId());
    }

}
